﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace X23.Application.SignalRManagement
{
    [Authorize]
    public class NotificationHub : Hub
    {
        public async override Task OnConnectedAsync()
        {
            var connectionId = Context.ConnectionId;
            var httpContext = Context.GetHttpContext();
            httpContext.Request.Query.TryGetValue("group_name", out StringValues groupName);
            httpContext.Request.Query.TryGetValue("access_token", out StringValues accessToken);

            if (!groupName.Equals(StringValues.Empty))
            {
                await Groups.AddToGroupAsync(connectionId, groupName);
            }
            await base.OnConnectedAsync();
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
            var connectionId = Context.ConnectionId;
            var httpContext = Context.GetHttpContext();
            httpContext.Request.Query.TryGetValue("group_name", out StringValues groupName);
            httpContext.Request.Query.TryGetValue("access_token", out StringValues accessToken);

            if (!groupName.Equals(StringValues.Empty))
            {
                await Groups.RemoveFromGroupAsync(connectionId, groupName);
            }

            await base.OnDisconnectedAsync(exception);
        }
    }
}
